import os, sys
sys.path[0:0] = ['framework']

import bottle
from bottle import request, response

from datamodel import Heater
from google.appengine.api import users

import datetime

# init

@bottle.route('/database_init')
def database_init():
    Heater.get_or_insert('demo', power = 'on')
    return 'done'

@bottle.route('/')
@bottle.route('/<filename:re:.*\.html>')
def static_html(filename = 'temperature.html'):
    list_user = ['duke@dukelec.com', 'heater@dukelec.com']
    user = users.get_current_user()
    if user == None:
        bottle.redirect(users.create_login_url("/"))
    if not any(x for x in list_user if x == user.email().lower()):
        return """
      <html><body>
        I'm very sorry, you(%s) are not in the access list, please contact duke{AT}dukelec.com
        <a href=\"%s\">sign out</a>
      </body></html>""" % (user.email().lower(), users.create_logout_url("/"))

    return bottle.static_file(filename, root='./')

# online test

@bottle.route('/keep_online_dev')
def dev_keep_online():
    heater = Heater.get_by_id('demo');
    heater.dev_online = long(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
    heater.put()
    return 'successed'

@bottle.route('/keep_online_web')
def web_keep_online():
    heater = Heater.get_by_id('demo');
    heater.web_online = long(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
    heater.put()
    return 'successed'

is_dev_online = False;
is_web_online = False;

def update_online_flag():
    global is_dev_online
    global is_web_online
    heater = Heater.get_by_id('demo');
    time_now = long(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
    if time_now > heater.dev_online + 60:
        is_dev_online = False
    else:
        is_dev_online = True
    if time_now > heater.web_online + 60:
        is_web_online = False
    else:
        is_web_online = True

@bottle.route('/check_online_dev')
def dev_check_online():
    update_online_flag()
    web_keep_online() # web check dev, so web keep online
    if is_dev_online:
        return 'online'
    return 'offline'

@bottle.route('/check_online_web')
def web_check_online():
    update_online_flag()
    dev_keep_online()
    if is_web_online:
        return 'online'
    return 'offline'

# check global_dirty
@bottle.route('/check_dirty')
def check_global_dirty():
    heater = Heater.get_by_id('demo')
    if heater.global_dirty == True:
        heater.global_dirty = False
        heater.put()
        return 'dirty'
    return 'clean'

# sys

@bottle.route('/sys.tt', method='POST')
def sys_for_user():
    command = request.POST.get('command', '')
    heater = Heater.get_by_id('demo')

    if command == 'get_timer':
        return heater.timer
    if command == 'get_date':
        return heater.date
    if command == 'get_power':
        return heater.power
    if command == 'get_hostname':
        return heater.dev_name

    if command == 'set_timer':
        heater.timer = request.POST.get('value', '')
        heater.timer_dirty = True
        heater.global_dirty = True
        heater.put()
        return 'successed'

# net

@bottle.route('/net.tt', method='POST')
def net_for_web():
    command = request.POST.get('command', '')
    heater = Heater.get_by_id('demo')

    if command == 'scan':
        return heater.wifi_list
    if command == 'get_connected':
        return heater.wifi_connected

    if command == 'connect':
        heater.wifi_set_ssid = request.POST.get('ssid', '')
        heater.wifi_set_passwd = request.POST.get('passwd', '')
        heater.wifi_set_dirty = True
        heater.global_dirty = True
        heater.put()
        return 'successed'

@bottle.route('/net', method='POST')
def net_for_dev():
    command = request.POST.get('command', '')
    heater = Heater.get_by_id('demo')

    #if command == 'connect_get':
    #    user2dev = Heater.get_by_id('demo');
    #    return user2dev.connect_ssid
    #    # how about passwd?

    value = request.POST.get('value', '')
    if command == 'update_scan':
        heater.wifi_list = value
    if command == 'update_connected':
        heater.wifi_connected = value
    heater.put()
    return 'successed'

# mcu

@bottle.route('/mcu.tt', method='POST')
def mcu_for_web():
    command = request.POST.get('command', '')
    heater = Heater.get_by_id('demo')

    if command == 'read_temperature':
        return heater.temp
    if command == 'read_humidity':
        return heater.humi
    if command == 'get_desired':
        return heater.desired

    if command == 'set_desired':
        heater.desired = request.POST.get('value', '')
        heater.desired_dirty = True
        heater.global_dirty = True
        heater.put()
        return 'successed'

@bottle.route('/mcu', method='POST')
def mcu_for_dev():
    command = request.POST.get('command', '')
    heater = Heater.get_by_id('demo')

    if command == 'get_desired':
        if heater.desired_dirty == True:
            heater.desired_dirty = False
            heater.put()
            return heater.desired
        else:
            return 'keep'

    value = request.POST.get('value', '')
    if command == 'update_temperature':
        heater.temp = value
    if command == 'update_humidity':
        heater.humi = value
    if command == 'update_desired':
        heater.desired = value
    heater.put()
    return 'successed'

# run

app = bottle.app()
bottle.run(app=app, server='gae', debug=False)
